package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 跳过登录接口和静态资源
        String uri = httpRequest.getRequestURI();
        if (uri.contains("/login") || uri.matches(".*\\.(css|js|jpg|png|ico)$")) {
            chain.doFilter(request, response);
            return;
        }

        // 这里可以添加登录验证逻辑，如检查 session 或 token
        Object user = httpRequest.getSession().getAttribute("user");
        if (user == null) {
            // 用户未登录，重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
            return;
        }

        chain.doFilter(request, response);
    }
}